package com.key.w8.http1.handler;

import com.key.w8.common.HttpSslConfigInitializer;
import com.key.w8.http1.connection.Connection;
import com.key.w8.http1.connection.ConnectionBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

/**
 * @Author: k8
 * @CreateTime: 2025-02-19
 * @Version: 1.0
 */
public abstract class AbstractHttp1Initializer extends ChannelInitializer<SocketChannel> implements HttpSslConfigInitializer {
    private boolean sslEnable;
    private Http1FullHandlerBuilder builder;
    private Connection connection;
    private boolean isServer;
    private ConnectionBuilder connectionBuilder;
    private String tsLProtocol;

    /**
     * Server
     * @param builder
     * @param sslEnable
     */
    public AbstractHttp1Initializer(ConnectionBuilder connectionBuilder,Http1FullHandlerBuilder builder, boolean sslEnable, String tsLProtocol, boolean isServer) {
        this.sslEnable = sslEnable;
        this.builder = builder;
        this.isServer = isServer;
        this.connectionBuilder = connectionBuilder;
        this.tsLProtocol = tsLProtocol;
    }

    /**
     * Client
     * @param connection
     * @param builder
     * @param sslEnable
     */
    public AbstractHttp1Initializer(Connection connection,Http1FullHandlerBuilder builder,boolean sslEnable, String tslProtocol,boolean isServer) {
        this.sslEnable = sslEnable;
        this.builder = builder;
        this.isServer = isServer;
        this.connection = connection;
        this.tsLProtocol = tslProtocol;
    }
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        if (isServer){
            pipeline.addLast("http1Handler",builder.build(connectionBuilder));
        }else {
            pipeline.addLast("http1Handler",builder.build(connection));
        }
        if (sslEnable) {
            SslContext sslContext = configSslContext(tsLProtocol);
            SslHandler sslHandler = sslContext.newHandler(ch.alloc());
            pipeline.addFirst("sslHandler", sslHandler);
        }

    }

}
